package com.bestcem.xm.survey.export.type;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.export.BaseTypeHandler;
import com.bestcem.xm.survey.grpc.client.dto.QstructsDto;
import org.springframework.stereotype.Component;

import java.util.*;

import static com.bestcem.xm.survey.enums.QuestionTypeEnum.QUESTION_TYPE_TIMEDELTA;

/**
 * 时间
 */
@Component
public class TimedeltaHandler implements BaseTypeHandler {

    @Override
    public Map<String, String> getOpenColumnChangeDictV2(JSONObject data) {
        Map<String, String> res = new HashMap(2);
        res.put(getOpenRealcolV2(data), getOpenReadablecolV2(data, false));
        return res;
    }

    private String getOpenReadablecolV2(JSONObject data, boolean convert) {
        if (convert) {
            String.format("%s（秒）", data.getString("title"));
        }
        return data.getString("title");
    }

    private String getOpenRealcolV2(JSONObject data) {
        return data.getString("cid");
    }

    @Override
    public List<String> getOpenColumnListV2(JSONObject data) {
        return Arrays.asList(getOpenRealcolV2(data));
    }

    @Override
    public Map<Object, Object> getOpenAnswerDictV2(JSONObject dataValue, Object answers) {
        Map<Object, Object> data = new HashMap<>();
        if (Objects.isNull(answers)) {
            //np.nan 可以理解为null
            data.put(getOpenRealcolV2(dataValue), null);
        } else {
            List<Integer> answersValue = (List) answers;
            if (ObjectUtil.isNotEmpty(answersValue)) {
                Integer value = answersValue.get(0);
                data.put(getOpenRealcolV2(dataValue), value);
                Float ts = Float.valueOf(value);
                int ts_min = (int) (ts / 60);
                int minute = ts_min % 60;
                int hour = ts_min / 60 % 60;
                data.put(getOpenRealcolV2(dataValue), String.format("%02d", hour) + ":" + String.format("%02d", minute));
            } else {
                data.put(getOpenRealcolV2(dataValue), null);
            }
        }
        return data;
    }

    @Override
    public List<List<String>> getVarLabelsV2(JSONObject dataValue, boolean not01, boolean need_title) {
        List<List<String>> data = new ArrayList<>();
        List<String> var_list = new ArrayList(), val_list = new ArrayList();
        var_list.add(String.format("VARIABLE LABELS %s '时间'.", getOpenRealcolV2(dataValue)));
        data.add(var_list);
        data.add(val_list);
        return data;
    }

    @Override
    public List<String> getSpssCodeV2(JSONObject param, QstructsDto qstruct) {
        List<String> head_list = new ArrayList();
        head_list.add(param.getString("cid"));
        return head_list;
    }

    @Override
    public String getQuestionTypeValue() {
        return QUESTION_TYPE_TIMEDELTA.getValue();
    }
}